package com.example.securitydemo.service;

import com.example.securitydemo.dao.UserDao;
import com.example.securitydemo.entity.Permission;
import com.example.securitydemo.entity.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务层：先模拟数据
 */
@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserDao userDao;

    /*private Map<String,UserDto> map = new HashMap<>();
    {
        map.put("zhangsan",new UserDto(1,"zhangsan","123456"));
        map.put("lisi",new UserDto(2,"lisi","123456"));
    }

    public UserDto login(String username,String password){
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new RuntimeException("参数有误");
        }
        UserDto userDto = map.get(username);
        if(userDto==null){
            throw new RuntimeException("用户不存在");
        }
        if(!password.equals(userDto.getPassword())){
            throw new RuntimeException("用户或密码不正确");
        }

        return userDto;
    }*/

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserDto userDto = userDao.getUserByUsername(s);
        if(userDto ==null){
            return null;
        }

        //根据用户id查询用户权限信息
        List<String> permissions = userDao.getPermissionByUsername(userDto.getId());
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities(permissionArray).build();
        return userDetails;
    }
}
